import Vue from 'vue'
import config from './configs';

// 添加Fastclick移除移动端点击延迟
import FastClick from 'fastclick'
FastClick.attach(document.body)

// 添加手势触摸事件，使用方法如 v-touch:swipeleft
import VueTouch from './plugins/touchEvent'
Vue.use(VueTouch)

import md5 from './utils/md5'
import cookie from './utils/cookie'

import util from './utils'
import $ from 'jquery'
import {m_jdbc2one,m_jdbc2many} from './imtsdk/jdbc'
import {Monad} from './imtsdk/monad'
import {create_im_token,get_im_token} from './imtsdk/nimapi'

var formData = new Vue({
  el: '#form-data',
  data: {
    logo: config.logo,
    account: '',
    password: '',
    nickname: '',
    errorMsg: ''
  },
  mounted () {
    this.$el.style.display = ""
  },
  methods: {
    regist () {
      if (this.account === '') {
        this.errorMsg = '帐号不能为空'
        return
      } else if (this.account.length > 20) {
        this.errorMsg = '帐号最多限20位'
        return
      } else if (/[^a-zA-Z0-9]/.test(this.account)) {
        this.errorMsg = '帐号限字母或数字'
        return
      } else if (this.nickname.length > 10) {
        this.errorMsg = '昵称限10位中文、英文或数字'
        return
      } else if (this.password === '') {
        this.errorMsg = '密码不能为空'
        return
      } else if (this.password.length < 6) {
        this.errorMsg = '密码至少需要6位'
        return
      }
      this.errorMsg = ''
      // 本demo做一次假登录
      // 真实场景应在此向服务器发起ajax请求
      m_jdbc2one(`select account,name nickname,password token from t_user where account='${this.account.trim()}'`)
      .bind(data=>{
          return  ! data
          ? m_jdbc2one(`insert into t_user(account,name,password) values('${this.account}','${this.nickname}','${this.token}')`)
          : Monad(data);
      }).bind(data=>{
          if(!data)data={account:this.account,name:this.nickname,token:this.password};
          return Monad(data);
      }).bind(data=>{
          create_im_token(data.account.toLowerCase(),data.name.toLowerCase())
          .then(res=>{
            console.log(res);
            if (res.code === 200) {
              m_jdbc2one(`update t_user set password='${res.info.token}' where account='${res.info.accid}'`)
              .bind(tt=>{
                let accountLowerCase = res.info.accid;
                let sdktoken = res.info.token;
                cookie.setCookie('uid', accountLowerCase)
                cookie.setCookie('sdktoken', sdktoken)
                location.href = config.routerBase+config.loginUrl
              });
            } else if (res.code === 414) {
              alert("用户已经注册，但账号密码不正确");
              this.errorMsg = data.errmsg
              location.href = config.routerBase+config.loginUrl
            } else {
              this.errorMsg = data.errmsg
            }
            this.$forceUpdate()
          });
      });
    },// regist
    login () {
      location.href = config.routerBase+config.loginUrl
    }
  },
})
